package com.zfb.ali.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.zfb.ali.config.AlipayProperties;
import com.zfb.ali.dto.CreateOrderDto;
import com.zfb.ali.service.PayService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ZFBPayServiceImpl implements PayService {

    @Resource
    private AlipayClient alipayClient;

    @Resource
    private AlipayProperties alipayProperties;

    @Value("${qrcode.width:200}")
    private int width;

    @Value("${qrcode.height:200}")
    private int height;

    @SneakyThrows
    @Override
    public void createOrderAndCode(CreateOrderDto createOrderDto, HttpServletResponse response) {
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setOutTradeNo(IdUtil.getSnowflake().nextIdStr()); //商户订单号
        model.setProductCode("FACE_TO_FACE_PAYMENT"); //销售产品码
        model.setSubject(alipayProperties.getSubject());  //订单标题
        model.setTotalAmount(String.valueOf(createOrderDto.getTotalAmount()));                  //订单总金额

        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setBizModel(model);
        request.setNotifyUrl(alipayProperties.getNotifyUrl());
        request.setReturnUrl(alipayProperties.getReturnUrl());

        AlipayTradePrecreateResponse alipayTradePrecreateResponse = alipayClient.execute(request);
        String content = alipayTradePrecreateResponse.getQrCode();

        log.info("下单返回内容:{}",JSONUtil.toJsonStr(content));
        makeQRCode(content, response.getOutputStream());
    }

    public void makeQRCode(String content, OutputStream outputStream) throws Exception {  //生成二维码
        Map<EncodeHintType, Object> map = new HashMap<>();
        map.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8);
        map.put(EncodeHintType.MARGIN, 2);

        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, map);
        MatrixToImageWriter.writeToStream(bitMatrix, "jpeg", outputStream);
    }
}
